﻿using AutoMapper;
using D.B.Data.API.Applications.Command;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler
{
    public class UPdateUserCommandHandler : IRequestHandler<UPdateUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> baseRepository;
        private readonly IMapper mapper;

        public UPdateUserCommandHandler(IBaseRepository<UserModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(UPdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var date = baseRepository.GetAll().Where(s => s.UserName== request.UserName&&s.Id!=request.Id);
            if(date.Count()>0)
            {
                result.Code = EnumCode.File;
                result.Msg = "名称重复";
                return Task.FromResult(result);
            }
            
            var res = baseRepository.GetAll().FirstOrDefault(s => s.Id == request.Id);
            res.Desc=request.Desc;
            res.UserName = request.UserName;
            res.UpDataTime = DateTime.Now;
            res.UpDataUserId = request.UserId;
            res.Sex = request.Sex;
            res.Shen = request.Shen;
            res.Xian = request.Xian;
            res.Shi = request.Shi;
            
           
            baseRepository.Update(res);
           
            result.Code = EnumCode.Ok;
            result.Msg = "修改成功";
            
            return Task.FromResult(result);

        }
    }
}
